import { Popup, Picker } from "vant";
// import Hybrid from "@/components/uzone-hybrid";
// import ubt from '@/service/ubt';
import MixinValidateForm from "@/service/mixin-validate-form";
import NavBar from "../components/navBar1";
// import { validateMobile, validateMobile9, validateMobile639, validateMobileA639 } from '@/libs/validate';
import doFaceButton from "@/components/doFaceButton";

export default {
  name: "contact-information",
  components: {
    NavBar,
    Popup,
    Picker,
    doFaceButton,
  },
  mixins: [MixinValidateForm],
  data() {
    return {
      productId: "",
      readonly: false,
      instalment: false,
      form: {
        relationshipFirst: "", // 联系人1关系
        contactFirst: "",
        phoneFirst: "",
        relationshipSecond: "", // 联系人2关系
        contactSecond: "",
        phoneSecond: "",
        relationshipThree: "",
        contactThree: "",
        phoneThree: "",
        // relationshipFour: "",
        // contactFour: "",
        // phoneFour: "",
        // relationshipFive: "",
        // contactFive: "",
        // phoneFive: "",
      },
      status: {
        identity: null,
        personal: null,
        work: null,
        contact: null,
        additional: null,
      },
      isAndriod7: false,
      contactType: "",
      relationshipData: [],
      isVisibleChooseRegion: false,
      isVisibleChooseRegionP: false,
      btnName: this.$t("next"),
      disabledBtn: false,
      BaseInfoData: {},
      relationshipList: [],
      pageTrackerInfo: {
        page: 'contactInfo',
        startTime: new Date().getTime()
      }
    };
  },
  computed: {
    btnCanSubmit() {
      const {
        relationshipFirst,
        contactFirst,
        phoneFirst,
        relationshipSecond,
        contactSecond,
        phoneSecond,
        relationshipThree,
        contactThree,
        phoneThree,
      } = this.form;
      return (
        !relationshipFirst ||
        !contactFirst ||
        !phoneFirst ||
        !relationshipSecond ||
        !contactSecond ||
        !phoneSecond ||
        !relationshipThree ||
        !contactThree ||
        !phoneThree
      );
    },
  },
  methods: {
    /**
     * 显示关系选择框
     */
    showRelationship(type) {
      this.contactType = type;
      if (type === "1") {
        this.relationshipData = ["Father", "Mother", "Spouse"];
      } else if (type === "2" || type === "4" || type === "5") {
        this.relationshipData = [
          "Father",
          "Mother",
          "Spouse",
          "Children",
          "Brothers And Sisters",
          "Friend",
          "Colleague",
        ];
      } else if (type === "3") {
        this.relationshipData = [
          "Father",
          "Mother",
          "Spouse",
          "Brothers And Sisters",
        ];
      }
      const list = [];
      this.relationshipData.forEach((item) => {
        const {
          relationshipFirst,
          relationshipSecond,
          relationshipThree,
          // relationshipFour,
          // relationshipFive,
        } = this.form;
        if (
          item !== relationshipFirst &&
          item !== relationshipSecond &&
          item !== relationshipThree
          // item !== relationshipFour &&
          // item !== relationshipFive
        ) {
          list.push(item);
        }
      });

      this.relationshipList = list;
      const eventName = `contactInfo_contact${type}_relation_click`
      this.$buryPoint.action({
        eventName,
        ...this.pageTrackerInfo
      });
      this.isVisibleChooseRegionP = true;
      setTimeout(() => {
        this.isVisibleChooseRegion = true;
      }, 100);
    },
    /**
     * 选择关系
     */
    chooseRegion(val) {
      // const params = {
      //   content: "",
      //   value: val,
      // };

      if (this.contactType === "1") {
        this.form.relationshipFirst = val;
        // params.content = "contact_page_first_related_select_done";
      }
      if (this.contactType === "2") {
        this.form.relationshipSecond = val;
        // params.content = "contact_page_second_related_select_done";
      }
      if (this.contactType === "3") {
        this.form.relationshipThree = val;
        // params.content = "contact_page_third_related_select_done";
      }
      // if (this.contactType === "4") {
      //   this.form.relationshipFour = val;
      //   params.content = "contact_page_fourth_related_select_done";
      // }
      // if (this.contactType === "5") {
      //   this.form.relationshipFive = val;
      //   params.content = "contact_page_fifth_related_select_done";
      // }
      // this.$hybrid.action("ee", {
      //   ...params,
      // });

      this.isVisibleChooseRegion = false;
      this.isVisibleChooseRegionP = false;
    },
    /**
     * 选择联系人
     */
    chooseContact(e, type) {
      if (this.readonly) {
        return;
      }

      this.contactType = type;
      const eventName = `contactInfo_contact${this.contactType}_num_click`
      // 联系人信息页 - 联系人 - 点击
      this.$buryPoint.action({
        eventName,
        ...this.pageTrackerInfo
      });
      const me = this;
      this.$hybrid.action("contact", {
        callback(data) {
          console.warn(data, "contact");
          if (data.status === 1) {
            if (data.data.status === 1) {
              const params = {
                eventName: `contactInfo_contact${me.contactType}_num_upload`,
              }
              let eventValue = {
                phone: data.data.data.tel,
                name: data.data.data.name,
              }
              if (me.contactType === "1") {
                me.form.contactFirst = data.data.data.name;
                me.form.phoneFirst = data.data.data.tel;
                eventValue.relation =  me.form.relationshipFirst
              }
              if (me.contactType === "2") {
                me.form.contactSecond = data.data.data.name;
                me.form.phoneSecond = data.data.data.tel;
                eventValue.relation =  me.form.relationshipSecond
              }
              if (me.contactType === "3") {
                me.form.contactThree = data.data.data.name;
                me.form.phoneThree = data.data.data.tel;
                eventValue.relation =  me.form.relationshipThree
              }
              params.eventValue = eventValue
              me.$buryPoint.action({
                ...params,
                ...me.pageTrackerInfo
              });
              me.phoneCheck(e.target, me.contactType, data.data.data.tel);
            } else {
              me.isAndriod7 = true;
              me.$toast("Unable to choose, please check permission");
            }
          }
        },
      });
    },
    /**
     * 获取页面数据
     */
    getData() {
      this.$api.queryUserContactsInfo().then((res) => {
        const { status, error, data } = res;
        if (
          "1" === status &&
          ("00000000" === error || "0000" === error) &&
          data
        ) {
          this.form = data;
        }
      });
    },
    /**
     * 获取资料填写度
     */
    getInfoData() {
      this.$api.getDataIntegrity().then((res) => {
        const { status, error, data } = res;
        if (
          "1" === status &&
          ("00000000" === error || "0000" === error) &&
          data
        ) {
          const status = this.status;
          status.identity = data.USERBASEINFO === "1"; // 基本信息
          status.personal = data.USERPERSONALINFO === "1"; // 个人信息
          status.work = data.USERJOB === "1"; // 工作信息
          status.contact = data.USERCONTACT === "1"; // 联系人信息
          status.additional = data.USERCARDID === "1"; // 身份信息
          if (data.USERCONTACT === "1") this.readonly = true;
          // if(data.USERBASEINFO === '1'&&data.USERPERSONALINFO === '1'&&data.USERJOB === '1'&&data.USERCONTACT==='1'&&data.USERCARDID === '1'){
          //   data.isEdit = '0'
          // }
          // this.readonly = this.readonly || data.isEdit === '0'; // 是否可编辑 0 不可编辑 1 可编辑
        }
      });
    },
    /**
     * 跳转填资
     */
    // goInformation(url) {
    //   const path = "/information/" + url;
    //   const instalment = this.instalment ? "true" : "false";
    //   this.$router.push({
    //     path,
    //     query: { productId: this.productId, instalment },
    //   });
    // },
    /**
     * 表单提交
     */
    submitHandler() {
      if (this.disabledBtn) return
      // 联系人信息页 - 提交 - 点击
      this.$buryPoint.action({
        eventName: 'contactInfo_page_submit_click',
        ...this.pageTrackerInfo
      });
      const form = this.form;
      if (!this.checkContact("contactForm")) {
        this.$toast("Please complete your information");
        return;
      }
      const arr = [
        form.relationshipFirst,
        form.relationshipSecond,
        form.relationshipThree
        // form.relationshipFour,
        // form.relationshipFive,
      ];
      if (this.checkSameRelationship(arr)) {
        this.$toast(this.$tc("contactRelationshipCanNotSame"));
        return;
      }
      const phoneList = [
        form.phoneFirst.replace(/\s*/g, ""),
        form.phoneSecond.replace(/\s*/g, ""),
        form.phoneThree.replace(/\s*/g, "")
        // form.phoneFour.replace(/\s*/g, ""),
        // form.phoneFive.replace(/\s*/g, ""),
      ];
      // if (phoneList.indexOf(this.BaseInfoData.phone) > -1 && [...new Set(phoneList)].length < phoneList.length) {
      // TODO 注：翻译记得加上
      if (
        this.BaseInfoData.phone &&
        phoneList.indexOf(this.BaseInfoData.phone) > -1
      ) {
        // 手机号不能和personal中的手机号相同
        this.$toast(this.$tc("contactPhoneCanNotSame"));
        return;
      }
      const newPhoneList = [];
      phoneList.forEach((item) => {
        if (item) {
          newPhoneList.push(item);
        }
      });

      const newSet = new Set(newPhoneList);

      if (newSet.size !== newPhoneList.length) {
        this.$toast("The number cannot be the same");
        return;
      }
      const user = this.$storage.get("user") || {};

      if (user.phone && phoneList.indexOf(user.phone) > -1) {
        // 手机号不能和personal中的手机号相同
        this.$toast("Mobile number cannot be the same");
        return;
      }
      /* if(!validateMobile(form.phoneFirst) && !validateMobile9(form.phoneFirst) && !validateMobile639(form.phoneFirst) && !validateMobileA639(form.phoneFirst) ) {
        this.$toast(this.$t('plsInputRightNumber') + this.$t('contact') + ' 1');
        return;
      }
      if(!validateMobile(form.phoneSecond) && !validateMobile9(form.phoneSecond) && !validateMobile639(form.phoneSecond) && !validateMobileA639(form.phoneSecond) ) {
        this.$toast(this.$t('plsInputRightNumber') + this.$t('contact') + ' 2');
        return;
      }
      if(!validateMobile(form.phoneThree) && !validateMobile9(form.phoneThree) && !validateMobile639(form.phoneThree) && !validateMobileA639(form.phoneThree) ) {
        this.$toast(this.$t('plsInputRightNumber') + this.$t('contact') + ' 3');
        return;
      }
      if(!validateMobile(form.phoneFour) && !validateMobile9(form.phoneFour) && !validateMobile639(form.phoneFour) && !validateMobileA639(form.phoneFour) ) {
        this.$toast(this.$t('plsInputRightNumber') + this.$t('contact') + ' 4');
        return;
      }
      if(form.phoneFive && !validateMobile(form.phoneFive) && !validateMobile9(form.phoneFive) && !validateMobile639(form.phoneFive) && !validateMobileA639(form.phoneFive) ) {
        this.$toast(this.$t('plsInputRightNumber') + this.$t('contact') + ' 5');
        return;
      }*/
      const params = {
        contactFirst: form.contactFirst,
        phoneFirst: form.phoneFirst,
        relationshipFirst: form.relationshipFirst,
        contactSecond: form.contactSecond,
        phoneSecond: form.phoneSecond,
        relationshipSecond: form.relationshipSecond,
        contactThree: form.contactThree,
        phoneThree: form.phoneThree,
        relationshipThree: form.relationshipThree,
        // contactFour: form.contactFour,
        // phoneFour: form.phoneFour,
        // relationshipFour: form.relationshipFour,
      };
      // if (form.contactFive && form.phoneFive && form.relationshipFive) {
      //   params.contactFive = form.contactFive;
      //   params.phoneFive = form.phoneFive;
      //   params.relationshipFive = form.relationshipFive;
      // }
      this.disabledBtn = true;
      // const hybrid = new Hybrid(this.$os.android ? 'android' : 'ios');
      this.$api
        .addOrUpdateUserContactsInfo(params)
        .then((res) => {
          const { status, error, msg } = res;
          if ("1" === status && ("00000000" === error || "0000" === error)) {
            this.$buryPoint.action({
              eventName: 'contactInfo_page_submit_success',
              ...this.pageTrackerInfo
            });
            this.$refs.checkFaceInfo.returnTo().catch(e => {
              this.disabledBtn = false;
            });
          } else {
            this.disabledBtn = false
            this.$toast(msg);
          }
        })
        .catch((error) => {
          this.disabledBtn = false;
        });
    },
    // appShowMain() {
    //   // const hybrid = new Hybrid(this.$os.android ? 'android' : 'ios');
    //   this.$hybrid.action("showMain", {
    //     param: { bool: false },
    //     callback(data) {},
    //   });
    // },
    checkSameRelationship(arr) {
      let isHasSameRelationship = false;
      for (let i = 0; i < arr.length; i++) {
        const temp = arr[i];
        let count = 0;
        for (let j = 0; j < arr.length; j++) {
          if (
            arr[j] == temp &&
            (arr[j] === "Father" ||
              arr[j] === "Mother" ||
              arr[j] === "Spouse" ||
              arr[j] === "Brothers And Sisters")
          ) {
            count++;
            arr[j] = -1;
          }
        }
        if (temp != -1 && count >= 2) {
          isHasSameRelationship = true;
        }
      }
      return isHasSameRelationship;
    },

    async getBaseInfo() {
      const res = await this.$api.qureyUserBaseInfo();
      const { status, error, data } = res;
      if (
        "1" === status &&
        ("00000000" === error || "0000" === error) &&
        data
      ) {
        this.BaseInfoData = data;
      }
    },
    phoneCheckInput(e, index) {
      const dom = e.target;
      this.phoneCheck(dom, index, dom.value);
    },
    phoneCheck(dom, indexLIst, tel) {
      const index = indexLIst * 1;

      if (isNaN(index)) {
        return;
      }

      const form = this.form;
      const phoneList = [
        form.phoneFirst,
        form.phoneSecond,
        form.phoneThree,
        form.phoneFour,
        form.phoneFive,
      ];
      const currentPhone = tel ? tel : phoneList[index];

      if (
        this.BaseInfoData.phone &&
        `${currentPhone}`.replace(/\s*/g, "") ===
          `${this.BaseInfoData.phone}`.replace(/\s*/g, "")
      ) {
        //this.markEle(dom);
        // 手机号不能和personal中的手机号相同
        this.$toast(this.$tc("contactPhoneCanNotSame"));
        return;
      }
      const newPhoneList = [];
      phoneList.forEach((item) => {
        if (item) {
          newPhoneList.push(item);
        }
      });

      const newSet = new Set(newPhoneList);

      if (newSet.size !== newPhoneList.length) {
        this.$toast("The number cannot be the same");
        return;
      }
      const user = this.$storage.get("user") || {};

      if (
        `${tel}`.replace(/\s*/g, "") === `${user.phone}`.replace(/\s*/g, "")
      ) {
        this.$toast("Mobile number cannot be the same");
        return;
      }
    },
  },
  created() {
    // this.appShowMain();
    const query = this.$route.query;
    this.productId = query.productId;
    if (query.btnType && query.btnType === "save") {
      // 按钮是下一步，还是保存
      this.btnName = this.$t("save");
    }
    this.readonly = query.readonly === "true";
    this.instalment = query.instalment === "true";
    this.getInfoData();
    this.getData();
    this.getBaseInfo();
  },
  beforeDestroy () {
    this.pageEndAction()
  },
  mounted () {
    // 联系人信息页 - 页面 - 曝光
    this.pageStartAction()
    this.$buryPoint.action({
      eventName: 'contactInfo_page_show',
      ...this.pageTrackerInfo
    });
  }
};
